//
//  DDMediaIV.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/12.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDMediaIV.h"
#import "DDTagDB.h"
#import "DDTagVC.h"

#import "MWPhoto.h"
#import "DDTagTextVC.h"
@implementation DDMediaIV

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addMedia:) name:@"addMedia" object:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeMedia:) name:@"removeMedia" object:nil];
        
        _diplayTags = [NSMutableArray array];
        _orderIndex = 0;
        //[self addMedias];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame;
{
    self = [super initWithFrame:frame];
    if (self) {
        //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addMedia:) name:@"addMedia" object:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeMedia:) name:@"removeMedia" object:nil];
        
        _diplayTags = [NSMutableArray array];
        _orderIndex = 0;
        //[self addMedias];
    }
    return self;
}

-(void)removeMedia:(NSNotification *)note
{
//    NSIndexPath *index = 
//    self viewWithTag:<#(NSInteger)#>
}

- (void)addMedias
{
    //_tags = [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%@'",_qid,_tagIndex] orderBy:@"rowid desc" offset:0 count:0];
    _tags = [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%@'",_qid,_tagIndex] orderBy:@"rowid desc" offset:0 count:0];
    
    for (int i = 0; i < _tags.count; i++) {
       DDTagDB *tagDB = _tags[i];
        if ([tagDB.type isEqualToString:@"IMAGE"]) {
            [self addImage:tagDB tag:i];
        }
        else if ([tagDB.type isEqualToString:@"AUDIO"]||[tagDB.type isEqualToString:@"VOICE"])
        {
            [self addAudio:tagDB tag:i];
        }
        else if ([tagDB.type isEqualToString:@"TEXT"])
        {
            [self addText:tagDB tag:i];
        }
    }
}

- (void)addImage:(DDTagDB *)tagDB tag:(NSInteger)index
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake([tagDB.x floatValue], [tagDB.y floatValue], 44, 44);
    //[button setTitle:@"文本" forState:UIControlStateNormal];
    [button addTarget:self  action:@selector(imagedisplay:) forControlEvents:UIControlEventTouchUpInside];
    NSLog(@"%ld",(long)tagDB.rowid);
    button.tag = tagDB.rowid+100;//index;
    [button setImage:[UIImage imageNamed:@"tag_photo"] forState:UIControlStateNormal];
    [self addSubview:button];
    
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 1.0;
    [button addGestureRecognizer:longPressGr];
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(handlePan:)];
    [button addGestureRecognizer:panGestureRecognizer];
}
- (void)addAudio:(DDTagDB *)tagDB tag:(NSInteger)index
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake([tagDB.x floatValue], [tagDB.y floatValue], 44, 44);
    //[button setTitle:@"文本" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"tag_audio"] forState:UIControlStateNormal];
    [button addTarget:self  action:@selector(audiodisplay:) forControlEvents:UIControlEventTouchUpInside];
    NSLog(@"%ld",(long)tagDB.rowid);
    button.tag = tagDB.rowid+100;//index;
    [self addSubview:button];
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 1.0;
    [button addGestureRecognizer:longPressGr];
    //longPressGr.view.tag = index;
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(handlePan:)];
    [button addGestureRecognizer:panGestureRecognizer];
}
- (void)addText:(DDTagDB *)tagDB tag:(NSInteger)index
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake([tagDB.x floatValue], [tagDB.y floatValue], 44, 44);
    //[button setTitle:@"文本" forState:UIControlStateNormal];
    NSLog(@"%ld",(long)tagDB.rowid);
    button.tag = tagDB.rowid+100;//index;
    [button setImage:[UIImage imageNamed:@"tag_text"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(textdisplay:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 1.0;
    
    [button addGestureRecognizer:longPressGr];
    
    
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(handlePan:)];
    [button addGestureRecognizer:panGestureRecognizer];
}

-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if( gesture.state == UIGestureRecognizerStateBegan){
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要移除标签？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //UIButton *button = (UIButton*)gesture.view;
    //    NSLog(@"%ld",(long)button.tag);
    alertView.tag = gesture.view.tag;
    [alertView show];
    }
}

- (void) handlePan:(UIPanGestureRecognizer*) recognizer
{
    
    CGPoint translation = [recognizer translationInView:self];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self];
    
    NSLog(@"X:%f====Y:%f",recognizer.view.center.x,recognizer.view.center.y);
    NSInteger tt =   recognizer.view.tag;
    if (tt-100 >= 0) {
        DDTagDB *db = [DDTagDB searchSingleWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)tt - 100] orderBy:nil];
        db.x = [NSString stringWithFormat:@"%f",recognizer.view.frame.origin.x];
        db.y = [NSString stringWithFormat:@"%f",recognizer.view.frame.origin.y];
        [db save];
    }
    
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSLog(@"%ld",(long)alertView.tag);
        NSInteger tt = alertView.tag-100;
        [[self viewWithTag:tt] removeFromSuperview];
        //[self setNeedsLayout];
        //[self layoutSubviews];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadDataTagDB" object:nil];
        [DDTagDB deleteWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)tt]];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"clearTagView" object:nil];
    if (!_isOnlyRead) {
        NSLog(@"%@",touches);
        NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
        UITouch *touch = [allTouches anyObject];   //视图中的所有对象
        CGPoint point = [touch locationInView:[touch view]]; //返回触摸点在视图中的当前坐标
        int x = point.x;
        int y = point.y;
        NSLog(@"touch (x, y) is (%d, %d)", x, y);
        if (_popMediaView) {
            _popMediaView(point);
        }
    }else{
        _photos = [NSMutableArray array];
        NSString *url = self.url;
        NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
        if (range.length >0)//包含
        {
            MWPhoto   *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            //photo.caption = _friendInfo.username;
            [_photos addObject:photo];
        }
        [[NSNotificationCenter defaultCenter]  postNotificationName:@"DisPlayImage" object:_photos];
    }
   
}



//- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
//    UITouch *touch = [allTouches anyObject];   //视图中的所有对象
//    CGPoint point = [touch locationInView:[touch view]]; //返回触摸点在视图中的当前坐标
//    int x = point.x;
//    int y = point.y;
//    NSLog(@"touch (x, y) is (%d, %d)", x, y);
//    if (_popMediaView) {
//        _popMediaView(point);
//    }
//}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   // NSLog(@"12312");
}

//-(void)addMedia:(NSNotification *)note
//{
//    DDTagVC *tagVC = note.object;
//    //NSLog(@"12312312");
//    if (tagVC) {
//        if ([tagVC.type isEqualToString:@"TEXT"]) {
//            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//            button.frame = CGRectMake([tagVC.x floatValue], [tagVC.y floatValue], 16, 16);
//            //[button setTitle:@"文本" forState:UIControlStateNormal];
//            [button setImage:[UIImage imageNamed:@"tag_text"] forState:UIControlStateNormal];
//            [button addTarget:self action:@selector(textdisplay) forControlEvents:UIControlEventTouchUpInside];
//            tag = tagVC;
//            [self addSubview:button];
//        }
//        else if([tagVC.type isEqualToString:@"AUDIO"])
//        {
//            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//            button.frame = CGRectMake([tagVC.x floatValue], [tagVC.y floatValue], 16, 16);
//            //[button setTitle:@"文本" forState:UIControlStateNormal];
//            [button setImage:[UIImage imageNamed:@"tag_audio"] forState:UIControlStateNormal];
//            [button addTarget:self  action:@selector(audiodisplay) forControlEvents:UIControlEventTouchUpInside];
//            tag = tagVC;
//            [self addSubview:button];
//        }
//        else if([tagVC.type isEqualToString:@"IMAGE"])
//        {
//            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//            button.frame = CGRectMake([tagVC.x floatValue], [tagVC.y floatValue], 16, 16);
//            //[button setTitle:@"文本" forState:UIControlStateNormal];
//            [button addTarget:self  action:@selector(imagedisplay) forControlEvents:UIControlEventTouchUpInside];
//            tag = tagVC;
//            [button setImage:[UIImage imageNamed:@"tag_photo"] forState:UIControlStateNormal];
//            [self addSubview:button];
//        }
//    }
//}

-(void)textdisplay:(UIButton *)sender
{
    if (sender.tag - 100 >= 0) {
        DDTagDB *db = [DDTagDB searchSingleWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)sender.tag - 100] orderBy:nil];
     
    //DDTagDB *db = _tags[sender.tag];
    NSLog(@"%@",db.result);
    NSDictionary *dict = @{@"result":db.result,@"type":@"TEXT",@"db":db};
 [[NSNotificationCenter defaultCenter] postNotificationName:@"displayMedia" object:dict];

    }
}

-(void)audiodisplay:(UIButton *)sender
{
    if (sender.tag - 100 >= 0) {
        DDTagDB *db = [DDTagDB searchSingleWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)sender.tag - 100] orderBy:nil];
    
    //DDTagDB *db = _tags[sender.tag];
    NSLog(@"%@",db.result);
   // NSLog(@"%@",tag);
    if (self.avPlay.playing) {
        [self.avPlay stop];
        return;
    }
    NSURL *url = [[NSURL alloc] initWithString:db.result]; //initFileURLWithPath:tag.voice.recordPath];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:data error:nil];
    self.avPlay = player;
    [self.avPlay play];
    }
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"displayMedia" object:tag];
}

-(void)imagedisplay:(UIButton *)sender
{
    if (sender.tag - 100 >= 0) {
        DDTagDB *db = [DDTagDB searchSingleWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)sender.tag - 100] orderBy:nil];//[[DDTagDB searchSingleWithWhere:[NSString stringWithFormat:@"rowid=%ld",(long)sender.tag - 100]] orderBy:nil] ;//_tags[sender.tag-100];
        NSLog(@"%@",db.result);
        NSDictionary *dict = @{@"result":db.result,@"type":@"IMAGE"};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"displayMedia" object:dict];
    }
    
}

//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//{
//     NSLog(@"%@",touches);
//}


- (void)dealloc
{
    [self removeFromSuperview];
}


-(void)addMedia:(NSString *)title type:(NSString *)type x:(double)x y:(double)y url:(NSString *)url;
{
    
    NSDictionary *dict = @{@"title":title?title:@"",@"type":type?type:@"",@"x":[NSNumber numberWithDouble:x],@"y":[NSNumber numberWithDouble:y],@"url":url?url:@""};
    [_diplayTags addObject:dict];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(x, y, 44, 44);
    //[button setTitle:@"文本" forState:UIControlStateNormal];
    button.tag = _orderIndex;
    _orderIndex++;
    if ([type isEqualToString:@"TEXT"]) {
        [button setImage:[UIImage imageNamed:@"tag_text"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(displayMedia:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([type isEqualToString:@"AUDIO"]||[type isEqualToString:@"VOICE"])
    {
        [button setImage:[UIImage imageNamed:@"tag_audio"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(displayAudio:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([type isEqualToString:@"IMAGE"])
    {
        [button setImage:[UIImage imageNamed:@"tag_photo"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(displayMedia:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self addSubview:button];
    
}



-(void)displayAudio:(UIButton *)sender
{
     if (_diplayTags.count > sender.tag) {
     NSDictionary *dict = _diplayTags[sender.tag];
    
    // NSLog(@"%@",tag);
    if (self.avPlay.playing) {
        [self.avPlay stop];
        return;
    }
    NSURL *url = [[NSURL alloc] initWithString:[dict objectForKey:@"url"]]; //initFileURLWithPath:tag.voice.recordPath];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:data error:nil];
    self.avPlay = player;
    [self.avPlay play];
     }
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"displayMedia" object:tag];
}
-(void)displayMedia:(UIButton *)button
{
    if (_diplayTags.count > button.tag) {
         NSDictionary *dict = _diplayTags[button.tag];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"displayMediaPP" object:dict];
    }
   
}

@end
